<?php

namespace app\admin\server;

use app\admin\model\wxwork\DepartModel;
use think\Db;
use think\Exception;

class DepartServer
{
    public static function synchronous()
    {
        try {
            $depart = QyApiWeixinServer::getDepartmentList();
            if($depart) {
                $data = [];
                foreach($depart as $item) {
                    $data[] = [
                        'id'               => $item['id'] ?? '',
                        'depart_name'      => $item['name'] ?? '',
                        'depart_en'        => $item['name_en'] ?? '',
                        'depart_leader'    => (isset($item['department_leader']) && !empty($item['department_leader']))
                            ? implode(',', $item['department_leader']) : '',
                        'depart_parent_id' => $item['parentid'],
                        'sorts'            => $item['order'] ?? 0,
                        'create_time'      => time(),
                    ];
                }
            }
            Db::transaction(function() use ($data) {
                $result = (new DepartModel())->insertAll($data, true);
            });
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    public static function getTree($depart_name = '', $pid = -1)
    {
        $where = [];
        !empty($depart_name) && $where[] = ['depart_name', 'like', '%' . $depart_name . '%'];
        $pid > -1 && $where[] = ['depart_parent_id', '=', $pid];

        $departs_tmp = DepartModel::field('id,depart_name,depart_parent_id as pid')
            ->where($where)
            ->order('id', 'desc')
            ->select();
//            ->toArray();
        if(empty($departs_tmp)) {
            return [];
        }
        foreach($departs_tmp as &$item) {
            $item = $item->toArray();
        }
        unset($item);
        return getDarray($departs_tmp, 0, 'son');
    }

}